package com.crm.miaohe.service;

import com.crm.miaohe.common.ApplicationConstant;
import com.crm.miaohe.config.FileProperties;
import com.crm.miaohe.controller.file.response.FileInfo;
import com.crm.miaohe.exception.ErpBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class FileUploadService {

    private final FileProperties fileProperties;

    public FileUploadService(FileProperties fileProperties) {
        this.fileProperties = fileProperties;
    }

    public FileInfo upload(MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            throw new ErpBusinessException(HttpStatus.BAD_REQUEST, new IllegalArgumentException("文件夹不存在"),
                    ApplicationConstant.COMMON_SERVER_ERR);
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //新文件名
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(fileProperties.getPath() + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        file.transferTo(dest);
        FileInfo fileInfo = new FileInfo();
        fileInfo.setFilePath(fileName);
        return fileInfo;
    }

}
